#include "productadd.h"
#include "ui_productadd.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QDir>
#include <QCoreApplication>
#include <QPixmap>
#include <QUuid>

productAdd::productAdd(QSqlDatabase db,QWidget *parent) :
    QDialog(parent),m_db(db),
    ui(new Ui::productAdd)
{
    ui->setupUi(this);

    // 设置状态选项
    ui->comboBoxStatus->addItem("在售");
    ui->comboBoxStatus->addItem("下架");
    ui->comboBoxStatus->addItem("缺货");

    // 设置价格范围
    ui->doubleSpinBoxPrice->setRange(0.01, 999999.99);
    ui->doubleSpinBoxPrice->setDecimals(2);

    // 设置库存范围
    ui->spinBoxStock->setRange(0, 99999);

    // 初始化图片标签
    ui->labelImage->setAlignment(Qt::AlignCenter);
    ui->labelImage->setStyleSheet("border: 1px solid #d0d0d0; background-color: #f8f8f8;");
    ui->labelImage->setMinimumSize(150, 150);
    ui->labelImage->setText("暂无图片");

    // 初始化编辑模式ID
    m_editProductId = -1;
}

productAdd::~productAdd()
{
    delete ui;
}

// 设置编辑模式下的商品数据
void productAdd::setProductData(int id, const QString &name, const QString &category,
                               double price, int stock, const QString &status, const QString &imagePath)
{
    m_editProductId = id;

    // 设置窗口标题为编辑模式
    setWindowTitle("编辑商品信息");
    ui->lineEditFlower_id->setText(QString::number(id));  // 将int转换为QString

    ui->lineEditName->setText(name);
    ui->lineEditCategory->setText(category);
    ui->doubleSpinBoxPrice->setValue(price);
    ui->spinBoxStock->setValue(stock);

    // 设置状态
    int statusIndex = ui->comboBoxStatus->findText(status);
    if(statusIndex >= 0) {
        ui->comboBoxStatus->setCurrentIndex(statusIndex);
    }

    // 加载图片
    if(!imagePath.isEmpty()) {
        QPixmap pix(imagePath);
        if(!pix.isNull()) {
            ui->labelImage->setPixmap(pix.scaled(ui->labelImage->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
            m_currentImagePath = imagePath;
        }
    }
}

// 选择图片按钮点击事件
void productAdd::on_pushButtonSelectImage_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择商品图片",
                                                   QDir::homePath(),
                                                   "图片文件 (*.png *.jpg *.jpeg *.bmp)");

    if(!fileName.isEmpty()) {
        QPixmap pix(fileName);
        if(pix.isNull()) {
            QMessageBox::warning(this, "错误", "无法加载图片文件");
            return;
        }

        // 创建应用目录下的图片文件夹
        QDir appDir(QCoreApplication::applicationDirPath());
        if(!appDir.exists("product_images")) {
            appDir.mkdir("product_images");
        }

        // 生成唯一文件名
        QFileInfo fileInfo(fileName);
        QString newFileName = "product_images/" + QUuid::createUuid().toString().remove('{').remove('}') + "." + fileInfo.suffix();
        QString destPath = QCoreApplication::applicationDirPath() + "/" + newFileName;

        // 复制文件到应用目录
        if(QFile::copy(fileName, destPath)) {
            // 更新UI显示
            ui->labelImage->setPixmap(pix.scaled(ui->labelImage->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
            m_currentImagePath = destPath;
        } else {
            QMessageBox::warning(this, "错误", "图片保存失败");
        }
    }
}

// 确认按钮点击事件
void productAdd::on_pushButtonOK_clicked()
{
    // 获取表单数据
    QString id = ui->lineEditFlower_id->text();
    QString name = ui->lineEditName->text().trimmed();
    QString category = ui->lineEditCategory->text().trimmed();
    double price = ui->doubleSpinBoxPrice->value();
    int stock = ui->spinBoxStock->value();
    QString status = ui->comboBoxStatus->currentText();

    // 验证输入
    if(id.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "商品ID不能为空");
        ui->lineEditFlower_id->setFocus();
        return;
    }
    if(name.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "商品名称不能为空");
        ui->lineEditName->setFocus();
        return;
    }

    if(category.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "商品分类不能为空");
        ui->lineEditCategory->setFocus();
        return;
    }

    if(price <= 0) {
        QMessageBox::warning(this, "输入错误", "商品价格必须大于0");
        ui->doubleSpinBoxPrice->setFocus();
        return;
    }

    // 准备数据库查询
    QSqlQuery query(m_db);

    if(m_editProductId > 0) {
        // 编辑模式 - 执行UPDATE
        query.prepare("UPDATE products SET name=?, category_id=?, price=?, stock=?, status=?, image_path=? WHERE product_id=?");
        query.addBindValue(name);
        query.addBindValue(category);
        query.addBindValue(price);
        query.addBindValue(stock);
        query.addBindValue(status);
        query.addBindValue(m_currentImagePath);
        query.addBindValue(m_editProductId);
    } else {
        // 添加模式 - 执行INSERT
        query.prepare("INSERT INTO products (product_id, name, category_id, price, stock, status, image_path) "
                      "VALUES (?, ?, ?, ?, ?, ?, ?)");
        query.addBindValue(id);
        query.addBindValue(name);
        query.addBindValue(category);
        query.addBindValue(price);
        query.addBindValue(stock);
        query.addBindValue(status);
        query.addBindValue(m_currentImagePath);
    }

    // 执行查询
    if(query.exec()) {
        if(m_editProductId > 0) {
            emit productUpdated();  // 发射更新信号
            QMessageBox::information(this, "成功", "商品信息更新成功");
        } else {
            emit productAdded();    // 发射添加信号
            QMessageBox::information(this, "成功", "商品添加成功");

            // 添加模式：清空表单，准备添加新商品
            ui->lineEditFlower_id->clear();
            ui->lineEditName->clear();
            ui->lineEditCategory->clear();
            ui->doubleSpinBoxPrice->setValue(0.01);  // 重置为最小值
            ui->spinBoxStock->setValue(0);
            ui->comboBoxStatus->setCurrentIndex(0);

            // 重置图片
            ui->labelImage->clear();
            ui->labelImage->setText("暂无图片");
            m_currentImagePath = "";

            // 将焦点设置回第一个输入框
            ui->lineEditFlower_id->setFocus();
        }
    } else {
        QMessageBox::critical(this, "错误", "保存失败: " + query.lastError().text());
    }
}

// 取消按钮点击事件
void productAdd::on_pushButtonCancel_clicked()
{
    this->hide();
}
